package com.joycessh.dao.impl;

import java.sql.*;

import com.joycessh.dao.UserDao;
import com.joycessh.util.DBConnectionManager;
import com.joycessh.vo.LoginVO;
import com.joycessh.vo.RegisterVO;

public class UserDaoImpl implements UserDao {
	/**
	 * @author joycessh
	 */
	
	DBConnectionManager dcm = null;
	Connection conn = null;
	Statement  stmt = null;
	ResultSet rs = null;
	PreparedStatement prepstmt = null;
	String sqlStr ="";
	Boolean flag = false;
	int effectLines = 0;
	
	@Override
	public boolean insertUser(RegisterVO user) throws SQLException {
		dcm = new DBConnectionManager();
		conn = dcm.getConnection();
		flag = false;
		
		sqlStr = "insert into user(username, password, role) values(?, ?, ?)";
		try {
			prepstmt = conn.prepareStatement(sqlStr);
			prepstmt.setString(1, user.getUsername());
			prepstmt.setString(2, user.getPassword());
			prepstmt.setString(3, "user");
			effectLines = prepstmt.executeUpdate();
			if (effectLines != 0) {
				flag = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		prepstmt.close();
		conn.close();
		return flag;
	}
	
	@Override
	public boolean isUsernameExist(String username) throws SQLException {
		dcm = new DBConnectionManager();
		conn = dcm.getConnection();
		flag = false;
		
		sqlStr = "select id from user where username=?";
		try {
			prepstmt = conn.prepareStatement(sqlStr);
			prepstmt.setString(1, username);
			rs = prepstmt.executeQuery();
			if (rs.next()) {
				flag = true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		rs.close();
		prepstmt.close();
		conn.close();
		return flag;
	}
	
	@Override
	public boolean checkUser(LoginVO user) throws SQLException {
		dcm = new DBConnectionManager();
		conn = dcm.getConnection();
		flag = false;
		
		sqlStr = "select id from user where username=? and password=?";
		try {
			prepstmt = conn.prepareStatement(sqlStr);
			prepstmt.setString(1, user.getUsername());
			prepstmt.setString(2, user.getPassword());
			rs = prepstmt.executeQuery();
			if (rs.next()) {
				flag = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		rs.close();
		prepstmt.close();
		conn.close();
		return flag;
	}
	
	@Override
	public boolean updatePassword(String username, String oldPassword, String newPassword) throws SQLException {
		dcm = new DBConnectionManager();
		conn = dcm.getConnection();
		flag = false;
		
		sqlStr = "update user set password=? where username=? and password=?";
		try {
			prepstmt = conn.prepareStatement(sqlStr);
			prepstmt.setString(1, newPassword);
			prepstmt.setString(2, username);
			prepstmt.setString(3, oldPassword);
			effectLines = prepstmt.executeUpdate();
			if (effectLines != 0) {
				flag = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		prepstmt.close();
		conn.close();
		return flag;
	}

}
